package com.yao.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yao.system.entity.Company;
import com.yao.system.entity.PageResult;
import com.yao.system.entity.Result;
import com.yao.system.entity.User;
import com.yao.system.entity.dto.CompanyUserDTO;
import com.yao.system.entity.dto.UserDTO;
import com.yao.system.mapper.UserMapper;
import com.yao.system.service.ICompanyService;
import com.yao.system.service.IUserService;
import com.yao.system.util.AppJwtUtil;
import com.yao.system.util.UserContext;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private final ICompanyService companyService;

    @Override
    public Result login(User user) {
        if (user == null) {
            return Result.error("用户信息不能为空");
        }
        String name = user.getName();
        String password = user.getPassword();
        if (StrUtil.isBlank(name) || StrUtil.isBlank(password)) {
            return Result.error("用户名或密码不能为空");
        }

        User result = lambdaQuery().eq(User::getName, name).one();
        if (result == null)
            return Result.error("用户不存在");
        String salt = result.getSalt();
        String pswd = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        if (!pswd.equals(result.getPassword())) {
            return Result.error("密码错误");
        }
        UserDTO userDTO = BeanUtil.copyProperties(result, UserDTO.class);
        if (result.getType() == 1) {
            userDTO.setCompany(
                    companyService.lambdaQuery()
                    .eq(Company::getUserId, result.getId())
                    .one()
                    .getName());
        }
        String token = AppJwtUtil.getToken2(userDTO);
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("user", userDTO);
        return Result.ok(map, "登陆成功");
    }

    @Override
    @Transactional
    public Result register(User user) {
        if (user == null || StrUtil.isBlank(user.getName()) ||
                StrUtil.isBlank(user.getPassword()) || StrUtil.isBlank(user.getSex())) {
            return Result.error("用户信息不能为空");
        }
        String name = user.getName();
        String password = user.getPassword();
        //if (StrUtil.isBlank(name) || StrUtil.isBlank(password)) {
        //    return Result.error("用户名或密码不能为空");
        //}

        User result = lambdaQuery().eq(User::getName, name).one();
        if (result != null)
            return Result.error("用户名已存在");

        if (StrUtil.isBlank(user.getImage())) {
            user.setImage("https://yao-ossbucket.oss-cn-hangzhou.aliyuncs.com/0ce8c9a3-40d5-4817-ac56-4734e12c0256.jpg");
        }
        String salt = UUID.randomUUID().toString();
        String pswd = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        user.setSalt(salt);
        user.setPassword(pswd);
        save(user);
        return Result.ok(null, "注册成功");
    }


    @Override
    @Transactional
    public Result companyRegister(CompanyUserDTO dto) {
        if (dto == null || StrUtil.isBlank(dto.getName()) ||
                StrUtil.isBlank(dto.getPassword()) || StrUtil.isBlank(dto.getSex())
                || StrUtil.isBlank(dto.getCompanyName()) || StrUtil.isBlank(dto.getPhone())
                || StrUtil.isBlank(dto.getAddress()) || StrUtil.isBlank(dto.getEmail())
                || StrUtil.isBlank(dto.getContact())) {
            return Result.error("用户信息不能为空");
        }
        User result = lambdaQuery().eq(User::getName, dto.getName()).one();
        if (result != null)
            return Result.error("用户名已存在");
        User user = new User();
        BeanUtil.copyProperties(dto, user);
        //user.setName(dto.getName());
        //user.setSex(dto.getSex());
        //user.setType(dto.getType());
        user.setImage("https://yao-ossbucket.oss-cn-hangzhou.aliyuncs.com/0ce8c9a3-40d5-4817-ac56-4734e12c0256.jpg");
        String salt = UUID.randomUUID().toString();
        String pswd = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());
        user.setSalt(salt);
        user.setPassword(pswd);
        save(user);
        Company company = new Company();
        BeanUtil.copyProperties(dto, company);
        company.setUserId(user.getId());
        company.setName(dto.getCompanyName());
        company.setIntroduction("无");
        company.setImage("https://yao-ossbucket.oss-cn-hangzhou.aliyuncs.com/a2a415a9-5796-4ac4-bdba-a22240c96936.jpg");
        companyService.save(company);
        return Result.ok(null, "注册成功");
    }

    @Override
    public Map<Long, User> getByIds(Set<Long> userIds) {

        List<User> list = lambdaQuery()
                .in(User::getId, userIds)
                .list();
        Map<Long, User> userMap = list.stream()
                .collect(Collectors.toMap(User::getId, user -> user));
        return userMap;
    }

    @Override
    @Transactional
    public Result updateUserInfo(User user) {
        if (user == null || StrUtil.isBlank(user.getName())) {
            return Result.error("修改失败，信息为空");
        }

        User result = lambdaQuery().eq(User::getName, user.getName()).one();
        if (result != null && !result.getId().equals(UserContext.getUser().getId()))
            return Result.error("修改失败,用户名已存在");

        if (StrUtil.isBlank(user.getPassword())) {
            user.setPassword(null);
            updateById(user);
            return Result.ok("修改成功");
        }
        UserDTO userDTO = UserContext.getUser();
        User userDb = getById(userDTO.getId());
        String salt = userDb.getSalt();
        String password = user.getPassword();
        String pswd = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        user.setId(userDTO.getId());
        user.setPassword(pswd);
        updateById(user);
        return Result.ok("修改成功");
    }

    @Override
    public Result getUserInfo() {
        UserDTO user = UserContext.getUser();
        User one = lambdaQuery()
                .eq(User::getId, user.getId())
                .one();
        one.setSalt(null);
        one.setCreateTime(null);
        one.setUpdateTime(null);
        return Result.ok(one);
    }

    @Override
    public Result queryUserList(Integer page, Integer size) {
        Page<User> userPage = lambdaQuery()
                .ne(User::getType, 2)
                .page(Page.of(page, size));
        List<User> userList = userPage.getRecords();
        int total = (int) userPage.getTotal();
        int pages = (int) userPage.getPages();
        if (CollectionUtil.isEmpty(userList)) {
            Result.ok(PageResult.of(total, pages, null));
        }
        return Result.ok(PageResult.of(total, pages, userList));
    }

    @Override
    @Transactional
    public Result updateUserAdmin(User user) {
        User user1 = new User();
        user1.setId(user.getId());
        user1.setName(user.getName());
        user1.setSex(user.getSex());
        user1.setType(user.getType());
        updateById(user1);
        return Result.ok("修改成功");
    }


}
